#include "tdownload.h"

TDownload::TDownload(QObject *parent, QStringList file_list) :
    QThread(parent), file_list(file_list)
{
    url.append("http://l2updater.seobrya.com/");
}
#include <QtDebug>

void TDownload::run()
{
    iterator = 0;
    if (iterator < file_list.size())
        startDownload();
    else
        this->quit();
    exec();
}
void TDownload::startDownload()
{
    path = file_list.at(iterator).section('/', 0, -2);
    qDebug() << "path=" << path;
    QUrl fileUrl(QString(url).append(file_list.at(iterator)));
    QFileInfo fileInfo(fileUrl.path());
    QString fileName = fileInfo.fileName();
    if (fileName.isEmpty())
        fileName = "noname";

    if (QFile::exists(fileName)){
        QFile::remove(fileName);
    }
    if (path != "" && !QDir(QString(".")).exists(path)){
        QDir(QString(".")).mkpath(path);
    }
    QString tmp(fileName);
    if (path != "")
        tmp.insert(0, path + "/");
    file = new QFile(tmp);
    if (!file->open(QIODevice::WriteOnly))
    {
        delete file;
        file = 0;
        return;
    }
    downloadFile(file_list.at(iterator));
}

void TDownload::downloadFile(QString filePath)
{
    emit changeStatus(QString("Downloading: ").append(filePath));
    current = new UniqueDl(0, filePath, file);
    connect(current, SIGNAL(done()), this, SLOT(chargementTermine()));
    connect(current, SIGNAL(updateProgress(int,int)), this, SLOT(downloadProgress(int,int)));
    current->start();
}

void TDownload::chargementTermine()
{
    iterator++;
    current->quit();
    emit done();
    if (iterator < file_list.size())
        startDownload();
    else
    {
        this->quit();
    }
}

void TDownload::downloadProgress(int un,int deux)
{
    emit updateProgress(un, deux);
}
